package com.gitee.xcfyl.simplehttpserver.io;

import java.io.IOException;
import java.io.InputStream;

/**
 * 封装了Http请求
 *
 * @author 西城风雨楼
 */
public class HttpRequest {
    /**
     * 请求的方法名称
     */
    private String method;

    /**
     * 本次请求的url
     */
    private String url;

    public HttpRequest(InputStream in) {
        try {
            parseHttpMessage(in);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 读取输入流中的数据，解析出当前Http请求的方法以及url
     *
     * @param in 输入流
     * @throws IOException 可能会抛出IO异常
     */
    private void parseHttpMessage(InputStream in) throws IOException {
        StringBuilder sb = new StringBuilder();
        byte[] bytes = new byte[2048];
        while (true) {
            int len = in.read(bytes);
            if (len <= 0) {
                break;
            }
            sb.append(new String(bytes, 0, len));
            if (len <= 1024) {
                break;
            }
        }
        String fistLine = sb.toString().split("\\n")[0];
        String[] fistLineArr = fistLine.split("\\s");
        this.method = fistLineArr[0];
        this.url = fistLineArr[1].split("\\?")[0];
    }

    public String getMethod() {
        return method;
    }

    public String getUrl() {
        return url;
    }
}
